String formatting [str.format()] with a dictionary having a key which is a str() of a number

Posted by decimus phostle on Stack Overflow See other posts from Stack Overflow or by decimus phostle
Published on 2012-06-21T02:30:14Z Indexed on 2012/06/21 3:16 UTC
Read the original article Hit count: 135

Filed under:
|
|

Python neophyte here. I was wondering if someone could help with the KeyError I am getting when using a dictionary for string interpolation in str.format.

dictionary = {'key1': 'val1', '1': 'val2'}

string1 = 'Interpolating {0[key1]}'.format(dictionary)
print string1

The above works fine and yields:

Interpolating val1

However doing the following:

dictionary = {'key1': 'val1', '1': 'val2'}

string2 = 'Interpolating {0[1]}'.format(dictionary)
print string2

results in:

Traceback (most recent call last):
  File "test.py", line 3, in <module>
    string2 = 'Interpolating {0[1]}'.format(dictionary)
KeyError: 1L

So the problem seems to be in the interpretation of the numeric key as a list index, IMHO. Is there any way to work around this? (i.e. convey that this is instead a dictionary key)

TIA and apologies if this question has been asked before(couldn't find anything relevant with my search-fu).

© Stack Overflow or respective owner

Related posts about python

Related posts about python-2.7